package com.cmxh.shipper.config;


import com.cmxh.shipper.util.Code;
import com.cmxh.shipper.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 未登录或者登录过期
@Component
public class MyNoLoginHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        // 告知我们给前端响应的是JSON格式，编码格式是UTF-8
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        Result r = new Result(Code.LOGIN_FAIL,"未登录或者登录过期");

        // 如何把对象转成json格式的字符串
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(r);
        httpServletResponse.getWriter().write(s);

        System.out.println(s);
        e.printStackTrace();// 权限不足的异常要打印
    }
}
